package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.dtos.WmNewsVo;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmNewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${fileServerUrl}")
    private String  file;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Override/*自媒体文章列表查询*/
    public ResponseResult findAll(WmNewsPageReqDto dto) {

        /*校验参数*/
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        QueryWrapper<WmNews> queryWrapper = new QueryWrapper<>();

        /*根据文章状态*/
        if (dto.getStatus()!=null){
            queryWrapper.lambda().eq(WmNews::getStatus,dto.getStatus());
        }
        /*根据文章关键字模糊*/
        if (dto.getKeyword()!=null){
            queryWrapper.lambda().like(WmNews::getTitle,dto.getKeyword());
        }
        /*根据频道id*/
        if (dto.getChannelId()!=null){
            queryWrapper.lambda().eq(WmNews::getChannelId,dto.getChannelId());
        }
        /*根据发布时间区间查询*/
        if (dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null){
            queryWrapper.lambda().between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }

        WmUser user = WmThreadLocalUtils.getUser();
        if (user!=null){
            queryWrapper.lambda().eq(WmNews::getUserId,user.getId());
        }

        queryWrapper.lambda().orderByDesc(WmNews::getCreatedTime);

        Page pageParam = new Page(dto.getPage(), dto.getSize());
        IPage result = page(pageParam,queryWrapper);

        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) result.getTotal());

        pageResponseResult.setData(result.getRecords());

        pageResponseResult.setHost(file);

        return pageResponseResult;
    }

    @Override/*发布自媒体文章*/
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {

        if (dto==null || dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        /*保存文章表*/
        WmNews wmNews = new WmNews();

        /*使用对象克隆*/
        BeanUtils.copyProperties(dto,wmNews);

        /*封面自动*/
        if (dto.getType().equals((short)-1)){
            wmNews.setType(null);
        }

        /*封面图片不为null*/
        if (dto.getImages()!=null && dto.getImages().size()>0){
            wmNews.setImages(dto.getImages().toString().replace("[","")
            .replace("]","").replace(file,"").replace(" ",""));
        }

        this.saveWmNews(wmNews,isSubmit);

        /*维护关系表 wmNewsMaterial*/
        String content = dto.getContent();
        /*将内容转成list集合泛型是map*/
        List<Map> contentList = JSON.parseArray(content, Map.class);
        /*调用私有方法  提取成只有url的集合*/
        List<String> materials = ectractUrlInfo(contentList);

        //解析图片  如果是1为提交审核  校验内容中的图片是否和素材库中的一致
        if (isSubmit==WmNews.Status.SUBMIT.getCode() && materials.size()>0){
            ResponseResult responseResult = saveRelativeInfoForContent(materials, wmNews.getId());
            if (responseResult.getCode()!=0){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
        }

        /*封面图片*/
        if (isSubmit == WmNews.Status.SUBMIT.getCode()){
            ResponseResult responseResult = saveRelativeInfoForCover(dto, materials, wmNews);
            if (responseResult.getCode()!=0){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override /*回显*/
    public ResponseResult findWmNewsById(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(id);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(file);
        return responseResult;
    }

    @Override/*删除*/
    public ResponseResult delNews(Integer id) {

        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = this.getById(id);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        /*如果是已发布 并且上架 不能删除*/
        if (wmNews.getStatus()==9 && wmNews.getEnable()==1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));

        this.removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override/*上下架 之前只对自媒体文章上下架 现在同步到ap端文章配置的上下架*/
    public ResponseResult downOrUp(WmNewsDto dto) {

        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        /*文章没有发布就没有上下架这个功能*/
        if (wmNews.getStatus()!=9){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        if (dto.getEnable()!=null && dto.getEnable()>-1 && dto.getEnable()<2) {

            if (wmNews.getArticleId()!=null){
                /*同步上下架  到articleConfig表*/
                Map<String ,Object> map = new HashMap<>();
                map.put("enable",dto.getEnable());
                map.put("articleId",wmNews.getArticleId());

                kafkaTemplate.send("enable_topic",JSON.toJSONString(map));
            }

        this.update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable, dto.getEnable()).eq(WmNews::getId, dto.getId()));
    }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override/*分页查询人工审核的文章列表 并且查出作者名称*/
    public PageResponseResult findListAndPage(NewsAuthDto dto) {

        if (dto==null){
            return (PageResponseResult)ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //设置起始页  公式    相当于 limit 的两个参数
        dto.setPage((dto.getPage()-1)*dto.getSize());

        /*分页查询数据*/
        List<WmNewsVo> list = wmNewsMapper.findListAndPage(dto);

        /*获取总条数*/
        int count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),count);
        responseResult.setData(list);
        responseResult.setHost(file);
        return responseResult;

    }

    @Override/*根据id 回显 人工审核的文章列表 并且查出作者名称*/
    public WmNewsVo findWmNewsVo(Integer id) {

        //1.查询文章信息
        WmNews wmNews = getById(id);
        //2.查询作者
        WmUser wmUser = null;
       if (wmNews!=null){
           wmUser = wmUserMapper.selectById(wmNews.getUserId());
       }
        //3.封装vo信息返回
        WmNewsVo wmNewsVo = new WmNewsVo();
       /*对象克隆*/
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }

        return wmNewsVo;



    }

    @Override/*使用job自动审核 状态为8 且 发布时间小于当前时间*/
    public List<Integer> findRelease() {
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 8).lt(WmNews::getPublishTime,new Date()));
        List<Integer> resultList = list.stream().map(WmNews::getId).collect(Collectors.toList());
        return resultList;
    }


    /*处理封面图片的逻辑*/
    private ResponseResult saveRelativeInfoForCover(WmNewsDto dto,List<String> contentImageList,WmNews wmNews){
        List<String> imagesList = dto.getImages();
        /*如果是自动 才会分配封面图片*/
        if (dto.getType().equals((short)-1)){
            /*设置单图*/
            if (contentImageList.size()>0 && contentImageList.size()<=2){
                wmNews.setType((short)1);
                imagesList = contentImageList.stream().limit(1).collect(Collectors.toList());
            }else if (contentImageList.size()>2){
                /*设置多图*/
                wmNews.setType((short)3);
                imagesList = contentImageList.stream().limit(3).collect(Collectors.toList());
            }else {
                /*设置无图*/
                wmNews.setType((short)0);
            }
        }
        if (imagesList!=null && imagesList.size()>0 ){
            wmNews.setImages(imagesList.toString().replace("[","")
            .replace("]","").replace(file,"").replace(" ",""));
        }
        this.updateById(wmNews);

        /*封面图片也要保存到关系表*/

        List<String> imageList = new ArrayList<>();
        for (String s : imagesList) {
            String image = s.replace(file, "");
            imageList.add(image);
        }
        ResponseResult responseResult = this.saveRelativeInfoForContent(imageList, wmNews.getId());

        if (responseResult.getCode()!=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /*公用的  处理内容的图片或者主图的图片 和素材表交集的数据  然后进行批量添加素材文章中间表*/
    private ResponseResult saveRelativeInfoForContent(List<String> contentImageList,Integer newsId){

        /*将图片的路径去素材表里查*/
        QueryWrapper<WmMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(WmMaterial::getUrl,contentImageList);
        WmUser user = WmThreadLocalUtils.getUser();
        if (user!=null) {
            queryWrapper.lambda().eq(WmMaterial::getUserId, user.getId());
        }

        List<WmMaterial> wmMaterialList = wmMaterialMapper.selectList(queryWrapper);


        /*map里面key是图片url value是id*/
        if (wmMaterialList!=null && wmMaterialList.size()>0) {
            Map<String, Integer> map = wmMaterialList.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));

        /*保存素材表ID*/
        List<String> materialsIds = new ArrayList<>();

        for (String url : contentImageList) {
            Integer id = map.get(url);
            if (id==null){
                /*图片不在素材库  应该 需要保存到素材库 以便之后使用*/
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }else {
                materialsIds.add(id.toString());
            }
        }

            /*批量保存素材文章关系表 三个参数 素材ID(List) 文章ID type(主图引用,文本引用)*/
        wmNewsMaterialMapper.saveRelationsByContent(materialsIds,newsId,(short) 1);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /*提取内容(content)的图片路径*/
    private List<String> ectractUrlInfo(List<Map> imageList){
        List<String> list = new ArrayList<>();
        for (Map map : imageList) {
            if (map.get("type").equals("image")){
                String image = (String) map.get("value");
                image = image.replace(file, "");
                list.add(image);
            }
        }
        return list;
    }


    /**
     * 保存或修改文章
     *
     * @param wmNews
     * @param isSubmit
     */
    private void saveWmNews(WmNews wmNews, Short isSubmit) {
        wmNews.setStatus(isSubmit);
        WmUser user = WmThreadLocalUtils.getUser();
        if (user!=null) {
            wmNews.setUserId(user.getId());
        }
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);



        boolean flag = false;

        if (wmNews.getId() == null) {
            flag = save(wmNews);
        } else {
            //如果是修改，则先删除素材与文章的关系
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(queryWrapper);
            flag = updateById(wmNews);
        }
        /*添加成功或修改成功 flag都为true 然后通过kafka发送消息*/
        if (flag){
            kafkaTemplate.send("auto_topic",JSON.toJSONString(wmNews.getId()));
        }
    }

}
